<?php

namespace App\Http\Controllers\Mobile;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\User;
use App\Models\Notice;
use App\Models\RefundGoods;

use App\Interfaces\OrderService;
use App\Interfaces\OrderGoodsService;
use App\Interfaces\CartService;

use Session,Auth,Input;

use App\Exceptions\Interfaces\OrderServiceException;
use Illuminate\Support\Collection;

class MyOrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request,OrderService $orderService)
    {
        $user = Auth::user();
        $page_size=6;
        $condations = $request->condations;                     //查询订单的条件
        //$page_size = empty($request->page)? 6 :$request->page;      //每页多少条数据

        if (empty($condations['order_status'])) {

            unset($condations['order_status']);
        }

        if (empty($condations['refund_goods'])) {

            unset($condations['refund_goods']);
        }

        $query = Order::select('order.*','user.user_name','order_goods.comment_status','order_goods.goods_id', 'refund_goods.refund_status')
            ->join('user','order.user_id','=','user.id')
            ->join('order_goods','order_goods.order_id','=','order.order_id')
            ->leftJoin('refund_goods','order.order_sn','=','refund_goods.order_sn')
            ->where('order.user_id',$user->id);

        //按订单状态筛选
        if(isset($condations['order_status'])&&$condations['order_status']!='all'){
            if($condations['order_status']==4){
                $query = $query->where('order.order_status',$condations['order_status'])->where('order_goods.comment_status','=',0);
            }else{
                $query = $query->where('order.order_status',$condations['order_status']);
            }

        }

        //按订单评论状态筛选
        if(isset($condations['comment_status'])&&$condations['comment_status']==0){
            $query = $query->where('order.order_status',4)->where('order_goods.comment_status','=',$condations['comment_status']);
        }//end if()

        //按订单时间筛选
        //$condations['date'] 1：近三个月；2：近一年；3：当年；4：去年；5：去年以前
        if(!empty($condations['date'])&&$condations['date']=='1'){
            $query = $query->where('order.add_time','>',date('Y-m-d H:i:s',strtotime('-3 month')));
        }//end if()

        if(!empty($condations['date'])&&$condations['date']=='2'){
            $query = $query->where('order.add_time','>',date('Y-m-d H:i:s',strtotime('-6 month')));
        }//end if()

        if(!empty($condations['date'])&&$condations['date']=='3'){
            $date = date("Y",strtotime(date('Y-m-d',time())));
            $query = $query->whereRaw('year(order.add_time)= '.$date);
        }//end if()

        if(!empty($condations['date'])&&$condations['date']=='4'){
            $date = date("Y",strtotime(date('Y-m-d',time())))-1;
            $query = $query->whereRaw('year(order.add_time)= '.$date);
        }//end if()

        if(!empty($condations['date'])&&$condations['date']=='5'){
            $date = date("Y",strtotime(date('Y-m-d',time())))-1;
            $query = $query->whereRaw('year(order.add_time)< '.$date);
        }//end if()

        //筛选退货订单
        if(!empty($condations['refund_goods'])){
            $query = $query->where('refund_goods.user_id', $user->id);
        }//end if()

        $orders = $query->groupBy('order_goods.order_id')->orderBy('order.add_time','desc')->paginate($page_size);

        foreach ($orders as $k=>$v) {
            $commentGoods = $orderService->getOrderGoods($v->order_id);
            foreach ($commentGoods as $goods) {
                if($goods->comment_status==0){
                    $v->comment_status=0;
                }
            }

        }

        foreach ($orders as $key => $value) {
            $order_id = $value->order_id;
            $order_goods = OrderGoods::select('goods.*','order_goods.buy_number','order_goods.id as order_goods_id','order_goods.comment_status')
                            ->leftJoin('goods', 'order_goods.goods_id', '=', 'goods.goods_id')
                            ->where('order_id', $order_id)
                            ->get();

            foreach ($order_goods as $order_goods_key => $order_goods_value) {

                $refundGoods = RefundGoods::where('order_sn', $value->order_sn)->where('goods_id', $order_goods_value->goods_id)->first();

                if ($refundGoods) {

                    $order_goods[$order_goods_key]->refund_status = $refundGoods->refund_status;
                }else{

                    $order_goods[$order_goods_key]->refund_status = null;
                }
            }
            $orders[$key]['order_goods'] = $order_goods->toArray();

        }//end foreach()

        return view('mobile.my.order',compact('user','status','page_size','query', 'orders', 'filter'));

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }


    /**
     * 订单详情页面
     * @param  [type]       $order_id     [订单id]
     * @param  OrderService $orderService [订单服务]
     * @return [type]                     [description]
     */
    public function show($order_id,OrderService $orderService)
    {

        try {

            $order = $orderService->getByOrderId($order_id);

        } catch (OrderServiceException $e) {

            /*$return['status'] = 0;

            $return['message'] = $e->getMessage();*/
            $order = new Collection();
        }
        $user = Auth::user();

        $notice = Notice::where('notice_id',$order_id)->first();

        $shopGoods = 0;

        $buyGoods = 0;

        $address_id = 0;

        //$orderService->calculateOrderGoods($shopGoods,$buyGoods,$address_id);

        //直辖市
        $cities = ['北京市', '天津市', '上海市', '重庆市'];

        return view('mobile.my.order_detail',compact('order','user','notice','cities'));

    }

    public function search(OrderService $orderService){

        $key = trim(Input::get('key'));

        $user = Auth::user();

        //直辖市
        $cities = ['北京市', '天津市', '上海市', '重庆市'];

        $order = $orderService->getByOrderSn($key, Auth::user()->id);

        if($order){

            $notice = Notice::where('notice_id',$order->order_id)->first();

            return view('mobile.my.order_detail',compact('order', 'user', 'notice', 'cities'));
        }else{

            return redirect()->back()->withInput()->withErrors('该订单不存在！');
        }

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除订单
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($order_id,Request $request)
    {

        // $order_id = $request->order_id;

        $order = Order::find($order_id);

        if($order->order_status==4||$order->order_status==5){

            $status = $order->delete();

            return response()->json(['status'=>$status]);

        }else{

            return response()->json(['status'=>0,'message'=>'只有已完成和已取消的订单可以删除！']);
        }
    }


    /**
     * 取消订单
     * @param  OrderService $orderService [description]
     * @param  Request      $request      [description]
     * @return [type]                     [description]
     */
    public function cancelOrder(OrderService $orderService,Request $request){

        $return = ['status'=>1, 'message'=>'取消成功', 'data'=>''];

        $order_id = $request->order_id;

        $reason = $request->reason;

        $user_id =  Auth::user()->id;

        if (empty($order_id)) {

            $return['status'] = 0;

            $return['message'] = '订单id不能为空';

            return response()->json($return);
        }


        try {

            $cancelOrder = $orderService->cancel($order_id,$reason,$user_id);

        } catch (OrderServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();
        }

        // return response()->json(['status'=>$cancelOrder]);

        return response()->json($return);

    }


    /**
     * 订单确认收货
     * @param  OrderService $orderService [description]
     * @param  Request      $request      [description]
     * @return [type]                     [description]
     */
    public function receiveGoods(OrderService $orderService,Request $request){

        $return = ['status'=>1, 'message'=>'确认成功', 'data'=>''];

        $order_id = $request->order_id;

        if (empty($order_id)) {

            $return['status'] = 0;

            $return['message'] = '订单id不能为空';

            return response()->json($return);
        }


        try {

            $order = $orderService->reciveGoods($order_id);

        } catch (OrderServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();
        }


        // return response()->json(['status'=>$order]);

        return response()->json($return);

    }


    /**
     * 订单提醒发货
     * @param  Request $request [description]
     * @param  Notice  $notice  [description]
     * @return [type]           [description]
     */
    public function remind(Request $request,Notice $notice){

        $return = ['status'=>1, 'message'=>'提醒成功', 'data'=>''];

        $param = $request->all();

        $param['notice_type'] = "订单发货";

        $param['notice_time'] = date('Y-m-d H:i:s');

        $param['user_id'] = Auth::user()->id;

        try {

            $notice = $notice->create($param);

            $return['status'] = $notice->id;

        } catch (OrderServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();
        }

        // return response()->json(['status'=>$notice->id]);

        return response()->json($return);

    }


    /**
     * 订单商品再次购买
     * @param  Request           $request           [description]
     * @param  OrderGoodsService $orderGoodsService [description]
     * @param  CartService       $cartService       [description]
     * @return [type]                               [description]
     */
    public function payagain(Request $request,OrderGoodsService $orderGoodsService, CartService $cartService)
    {

        $return = ['status'=>1, 'message'=>'再次购买成功', 'data'=>''];

        if(empty($request->get('order_id'))){

            $return['status'] = 0;

            $return['message'] = '订单id不能为空';

            return Response()->json($return);
        }

        $orderGoods = $orderGoodsService->getOrderGoodsById($request->get('order_id'));

        if (empty($orderGoods)) {

            $return['status'] = 0;

            $return['message'] = '订单商品不存在';

            return Response()->json($return);
        }

        foreach($orderGoods as $key=>$goods){

            $goods_id = $goods['goods_id'];

            $goods_num = $goods['buy_number'];

            if(empty($goods_id)){

                $return['status'] = 0;

                $return['message'] = '商品id不能为空';

                return Response()->json($return);
            }

            if(empty($goods_num)){

                $return['status'] = 0;

                $return['message'] = '商品【'.$goods['goods_name']."】数量不能为空";

                return Response()->json($return);
            }
            //dd("Dg");
            try{

                $cartService->addGoods($goods_id,$goods_num);

                $cartNum=$cartService->getCartNumber();

                $return['goods_num'] = $cartNum;

            } catch (InvalidArgumentException $e) {
                $return['message'] = $e->getMessage();

            }//end try

        }//end foreach

        //dd($goods['goods_id']);
        return Response()->json($return);

    }//end func payagain


    public function getOrder(Request $request,OrderService $orderService){
        $user = Auth::user();

        $page_size=6;
        $condations = $request->condations;                     //查询订单的条件

        if (empty($condations['order_status'])) {

            unset($condations['order_status']);
        }

        if (empty($condations['refund_goods'])) {

            unset($condations['refund_goods']);
        }

        $query = Order::select('order.*','user.user_name','order_goods.comment_status','order_goods.goods_id', 'refund_goods.refund_status')
            ->join('user','order.user_id','=','user.id')
            ->join('order_goods','order_goods.order_id','=','order.order_id')
            ->leftJoin('refund_goods','order.order_sn','=','refund_goods.order_sn')
            ->where('order.user_id',$user->id);


        //按订单状态筛选
        if(isset($condations['order_status'])&&$condations['order_status']!='all'){
            if($condations['order_status']==4){
                $query = $query->where('order.order_status',$condations['order_status'])->where('order_goods.comment_status','=',0);
            }else{
                $query = $query->where('order.order_status',$condations['order_status']);
            }

        }

        //按订单评论状态筛选
        if(isset($condations['comment_status'])&&$condations['comment_status']==0){
            $query = $query->where('order.order_status',4)->where('order_goods.comment_status','=',$condations['comment_status']);
        }//end if()

        //按订单时间筛选
        //$condations['date'] 1：近三个月；2：近一年；3：当年；4：去年；5：去年以前
        if(!empty($condations['date'])&&$condations['date']=='1'){
            $query = $query->where('order.add_time','>',date('Y-m-d H:i:s',strtotime('-3 month')));
        }//end if()

        if(!empty($condations['date'])&&$condations['date']=='2'){
            $query = $query->where('order.add_time','>',date('Y-m-d H:i:s',strtotime('-6 month')));
        }//end if()

        if(!empty($condations['date'])&&$condations['date']=='3'){
            $date = date("Y",strtotime(date('Y-m-d',time())));
            $query = $query->whereRaw('year(order.add_time)= '.$date);
        }//end if()

        if(!empty($condations['date'])&&$condations['date']=='4'){
            $date = date("Y",strtotime(date('Y-m-d',time())))-1;
            $query = $query->whereRaw('year(order.add_time)= '.$date);
        }//end if()

        if(!empty($condations['date'])&&$condations['date']=='5'){
            $date = date("Y",strtotime(date('Y-m-d',time())))-1;
            $query = $query->whereRaw('year(order.add_time)< '.$date);
        }//end if()

        //筛选退货订单
        if(!empty($condations['refund_goods'])){
            $query = $query->where('refund_goods.user_id', $user->id);
        }//end if()


        $orders = $query->groupBy('order_goods.order_id')->orderBy('order.add_time','desc')->paginate($page_size);

        foreach ($orders as $k=>$v) {
            $commentGoods = $orderService->getOrderGoods($v->order_id);
            foreach ($commentGoods as $goods) {
                if($goods->comment_status==0){
                    $v->comment_status=0;
                }
            }

        }

        foreach ($orders as $key => $value) {
            $order_id = $value->order_id;
            $order_goods = OrderGoods::select('goods.*','order_goods.buy_number','order_goods.id as order_goods_id','order_goods.comment_status')
                ->leftJoin('goods', 'order_goods.goods_id', '=', 'goods.goods_id')
                ->where('order_id', $order_id)
                ->get();

            foreach ($order_goods as $order_goods_key => $order_goods_value) {

                $refundGoods = RefundGoods::where('order_sn', $value->order_sn)->where('goods_id', $order_goods_value->goods_id)->first();

                if ($refundGoods) {

                    $order_goods[$order_goods_key]->refund_status = $refundGoods->refund_status;
                }else{

                    $order_goods[$order_goods_key]->refund_status = null;
                }
            }

            $orders[$key]['order_goods'] = $order_goods->toArray();

        }//end foreach()

        return view('mobile.my.get_order',compact('user','status','page_size','orders','filter'));
    }

}
